package com.bill99.service.impl;

import com.bill99.http.util.HttpClient;
import com.bill99.model.TableauProperties;
import com.bill99.schedule.SendDTSRunningTaskDashboardTask;
import com.bill99.service.TableauService;
import com.bill99.util.JsonUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Service(value = "tableauServiceImpl")
public class TableauServiceImpl implements TableauService {

    private static final  Logger LOGGER = LoggerFactory.getLogger(SendDTSRunningTaskDashboardTask.class);
    private String urlPrefix = "https://tableau.99bill.net/api/2.8/sites/";
    @Override
    public void generatePic(TableauProperties tableau)throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        //tabaleau用户名
        param.put("name", tableau.getName());
        //tableau密码
        param.put("password", tableau.getPassword());
        Map<String, String> uri = new HashMap<String, String>();
        uri.put("contentUrl", tableau.getContentUrl());
        param.put("site", uri);

        params.put("credentials", param);
        String result = jsonPost(tableau.getUrl(), params);
        Map<String, Object> jsonMap = JsonUtil.convert2Object(result, new HashMap<String, Object>());
//		//发送post请求获取项目列表
        Map<String, Object> creMap = (Map<String, Object>) jsonMap.get("credentials");
        Map<String, Object> siteMap = (Map<String, Object>) creMap.get("site");
        String siteID = (String) siteMap.get("id");
        String token = (String) creMap.get("token");
        String urlck = "https://tableau.99bill.net/api/2.8/sites/" + siteID + "/views/" +tableau.getViewId()+"/image";
//		//发送get请求
        HttpClient client = new HttpClient();
        client.getPic(urlck, token,tableau.getUploadPath());
    }

    public List<String> generatePicByWorkbook(TableauProperties myTableau,TableauProperties tableau) throws Exception {
        Map<String, Object> siteInfo = querySiteID(tableau);
        String workbookName = "新数据平台运行状态";

        String siteID = (String) siteInfo.get("id");
        String token = (String) siteInfo.get("token");

        //获取workbook-id
        String workbookID = queryWorkbookID(siteID, token, workbookName);

        if(null != workbookID){
            //获取views-id
            Map<String, String> viewsID = queryViewsID(siteID,workbookID,token);
            HttpClient client = new HttpClient();

            List<String> picNames = new ArrayList<String>();
            for(Map.Entry<String, String> entry : viewsID.entrySet()){
                String urlck = urlPrefix + siteID + "/views/"+entry.getKey()+"/image";
                String uploadPath = myTableau.getUploadPath()+ entry.getValue();
                picNames.add(entry.getValue()+".png");
                client.getPics(urlck, token,uploadPath);
            }
            System.out.println("picNames list:" +picNames.toString());
            return picNames;
        }
        else
            return null ;
    }
    public String queryWorkbookID(String siteID, String token, String workbookName) throws Exception {

        String urlck = urlPrefix +siteID + "/workbooks/";
// 		//发送get请求
        HttpClient client = new HttpClient();
        String workbookResult = client.get(urlck, token).toString();
        JSONArray xmlJsonArray = XML.toJSONObject(workbookResult).getJSONObject("tsResponse").getJSONObject("workbooks").getJSONArray("workbook");

        for(int i=0;i<xmlJsonArray.length();i++){
            JSONObject jo = xmlJsonArray.getJSONObject(i);
            if(workbookName.equals(jo.get("name").toString())){
                return (String)jo.get("id");
            }
        }
        return null;

    }

    public Map<String, Object> querySiteID(TableauProperties tableau) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        //tableau用户名
        param.put("name", tableau.getName());
        //tableau密码
        param.put("password", tableau.getPassword());
        Map<String, String> uri = new HashMap<String, String>();
        uri.put("contentUrl", tableau.getContentUrl());
        param.put("site", uri);
        params.put("credentials", param);

        String result = jsonPost(tableau.getUrl(), params);
        Map<String, Object> jsonMap = JsonUtil.convert2Object(result, new HashMap<String, Object>());
//		//发送post请求获取项目列表
        Map<String, Object> creMap = (Map<String, Object>) jsonMap.get("credentials");
        Map<String, Object> siteMap = (Map<String, Object>) creMap.get("site");
        String siteID = (String) siteMap.get("id");
        String token = (String) creMap.get("token");

        Map<String, Object> siteInfo = new HashMap<String, Object>();
        siteInfo.put("id", siteID);
        siteInfo.put("token",token);
        return siteInfo;

    }

    public String queryProjectID(String siteID, String token, String projectName) throws Exception {

        String urlck = urlPrefix +siteID + "/projects/";
// 		//发送get请求
        HttpClient client = new HttpClient();
        String projectsResult = client.get(urlck, token).toString();
        JSONArray xmlJsonArray = XML.toJSONObject(projectsResult).getJSONObject("tsResponse").getJSONObject("projects").getJSONArray("project");

        for(int i=0;i<xmlJsonArray.length();i++){
            JSONObject jo = xmlJsonArray.getJSONObject(i);
            if(projectName.equals(jo.get("name").toString())){
                return (String)jo.get("name") ;
            }
        }
        return null;
    }



    public Map<String, String> queryViewsID(String siteID, String workbookID, String token){
        String urlck = urlPrefix +siteID + "/workbooks/" + workbookID + "/views";
//		//发送get请求
        HttpClient client = new HttpClient();
        String workbookResult = (String)client.get(urlck, token);
        Map<String, String> map = new LinkedHashMap<String, String>();

        JSONArray xmlJsonArray;
        try {
            xmlJsonArray = XML.toJSONObject(workbookResult).getJSONObject("tsResponse").getJSONObject("views").getJSONArray("view");

            for(int i=0;i<xmlJsonArray.length();i++){
                JSONObject jo = xmlJsonArray.getJSONObject(i);
                map.put(jo.get("id").toString(), jo.get("name").toString());
            }

        } catch (JSONException e) {
            LOGGER.info("TableauServiceImpl queryViewsID",e.getMessage());
        }
        return map;
    }

    /**
     * 发送HttpPost请求
     *
     * @param strURL 服务地址
     * @param params
     * @return 成功:返回json字符串<br/>
     */
    public static String jsonPost(String strURL, Map<String, Object> params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(JsonUtil.convert2Json(params));
            out.flush();
            out.close();

            int code = connection.getResponseCode();
            InputStream is = null;
            if (code == 200) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }

            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                return result;
            }

        } catch (IOException e) {
//            LOG.error("Exception occur when send http post request!", e);
        }
        return "error"; // 自定义错误信息
    }


}
